import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';

export const POST = withMiddleware(async (request: NextRequest) => {
  // 身份验证
  await authenticateRequest(request);

  const body = await request.json();
  const { page = 1, pageSize = 10, siteName, category, status, email } = body;

  // 构建查询条件
  const where: any = {};
  
  if (siteName) {
    where.siteName = {
      contains: siteName,
      mode: 'insensitive',
    };
  }
  
  if (category) {
    where.category = category;
  }
  
  if (status !== undefined) {
    where.status = status;
  }
  
  if (email) {
    where.email = {
      contains: email,
      mode: 'insensitive',
    };
  }

  // 获取总数
  const total = await prisma.submission.count({
    where,
  });

  // 获取分页数据
  const submissions = await prisma.submission.findMany({
    where,
    orderBy: { createdAt: 'desc' },
    skip: (page - 1) * pageSize,
    take: pageSize,
  });

  const formattedSubmissions = submissions.map((submission: any) => ({
    ...submission,
    createdAt: submission.createdAt.toISOString(),
    updatedAt: submission.updatedAt.toISOString(),
  }));

  return {
    data: formattedSubmissions,
    total,
    page,
    pageSize,
  };
});